package gbench.sandbox.matlib;

import org.junit.jupiter.api.Test;

import java.math.BigInteger;
import java.util.function.Function;

import gbench.common.matlib.data.DataReader.DFrame;
import gbench.common.matlib.data.Pipe;
import gbench.common.tree.LittleTree;
import gbench.common.tree.LittleTree.IRecord;
import gbench.common.tree.LittleTree.Term;
import gbench.commonApp.data.DataApp;

import static gbench.common.tree.LittleTree.IRecord.*;
import static gbench.common.tree.LittleTree.trycatch;
import static gbench.common.matlib.MatlibCanvas.println;

/**
 * DataFrame Application 的数据库引用演示
 * @author gbench
 *
 */
public class JunitDfmApp {
    
    /**
     * 默认数据库
     * 
     * @author gbench
     *
     */
    class MyDataApp extends DataApp {
        /**
         * 构造函数:进行数据库配置
         */
        public MyDataApp() {
            this.getConfigure().set("url","jdbc:mysql://localhost:3306/information_schema?useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=True");
            this.reload();
        }
    }

    @Test
    public void foo() {
        final var dataApp = new MyDataApp();// 创建数据应用
        dataApp.withTransaction(sess -> {
            final var df = Pipe.DUMMY(String.class)
                    .bind(trycatch(sess::sql2records)).bind(IRecord::ROWS2COLS)
                    .bind(DFrame::new); // df 运算函数
            final var schemainfo = REC("#table_schema", "information_schema", "#table_name", "PROCESSLIST"); // 数据库字典
            final var tidy = Pipe.DUMMY(String.class)
                    .bind(line -> Term.FT(line, schemainfo)) // 模版填充
                    .bind(Term::percent_tidyline);// %清理
            final var metasql = "select column_name,column_comment, data_type from information_schema.columns where table_schema=#table_schema and table_name=#table_name";
            final var meta = df.eval(tidy.eval(metasql));
            println("columns", meta);
            final var kvps = meta.rcollect2(rclc2);
            LittleTree.timeit(() -> {
                final var dfm = df.eval(tidy.eval(("select * from %#table_schema.%#table_name limit 1000")))
                        .dataframe2(rec -> rec.aoks2rec(k -> kvps.compute(k, (String _k, String v) -> v.isBlank() ? _k : v)))
                        .rfilter(test("ID", (BigInteger id) -> id.intValue() < 1000)); // 行号清理,提取ID小于1000的数据记录
                println(dfm);
                println(dfm.eval((Function<IRecord, Object>) e -> e.get("id")));
            });// timeit
        }); // withTransaction
    }

}
